﻿using Library.Common.Model;
using Library.Common.Serialize;
using Library.Core.Application;
using Library.Core.Application.BaseAction;
using Library.Core.Application.IInfrastructure;
using Synthesize.BaseSet.Domain.Aggregation.Entity.Authority;
using Synthesize.BaseSet.Domain.Repository.Authority;
using Synthesize.BaseSet.Domain.Specifications.Authority.Department;
using Synthesize.BaseSet.ServiceInterface.Dtos.Authority.Department;
using Synthesize.BaseSet.ServiceInterface.Query.Authority;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Synthesize.BaseSet.Application.Query.Authority
{
    /// <summary>
    /// 部门查询逻辑类
    /// </summary>
    public class DepartmentQueryService : BaseService, IDepartmentQueryService
    {

        private readonly IDepartmentRepository _departmentRepository;

        public DepartmentQueryService(IIocContainer container
            , IDepartmentRepository departmentRepository
            ) : base(container)
        {
            _departmentRepository = departmentRepository;
        }

        /// <summary>
        /// 获取部门树
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BaseApiResult<List<GetDepartmentTreeListOutput>>> GetDepartmentTree(GetDepartmentTreeListInput input) {

            return await HandleAsync(input, async () =>
            {
                var result = new List<GetDepartmentTreeListOutput>();

                var spceifications = new GetDepartmentListSpceification(input.Keywords,input.RootId).SatisfiedBy();
                var departmentList = await _departmentRepository.GetDepartmentTree(spceifications, input.ReadOnly);

                if (departmentList.Any())
                {
                    var roots = new List<DepartmentInfoEntity>();
                    if (departmentList.Exists(x => !x.ParentId.HasValue))
                    {
                        roots = departmentList.Where(x => !x.ParentId.HasValue).ToList();
                    }
                    else {
                        var idList = departmentList.Select(x => x.Id).Distinct().ToList();
                        roots = departmentList.Where(x => !idList.Contains(x.ParentId.Value)).ToList();
                    }
                    result = MapperHelper<DepartmentInfoEntity, GetDepartmentTreeListOutput>.MapList(roots);
                    foreach (var root in result)
                    {
                        GetChildDepartment(root, departmentList);
                    }
                }

                return result;
            });
        }

        /// <summary>
        /// 获取子节点
        /// </summary>
        /// <param name="root"></param>
        /// <param name="dataList"></param>
        private void GetChildDepartment(GetDepartmentTreeListOutput root, List<DepartmentInfoEntity> dataList)
        {
            var childrens = dataList.Where(x => x.ParentId == root.Id).OrderBy(x => x.Sort).ToList();
            if (childrens.Any())
            {
                var parents = MapperHelper<DepartmentInfoEntity, GetDepartmentTreeListOutput>.MapList(childrens);
                root.Children = parents;

                foreach (var item in parents)
                {
                    GetChildDepartment(item, dataList);
                }
            }
        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetDepartmentListOutput>> GetDepartmentList(GetDepartmentListInput input) {

            var resultList = new List<GetDepartmentListOutput>();
            //获取对应的整个树结构
            var departments = await _departmentRepository.GetManyAsync(x => true);
            if (departments.Any())
            {
                if (input.RootId.HasValue)
                {
                    var root = departments.FirstOrDefault(x => x.Id == input.RootId.Value);
                    var rootInfo = MapperHelper<DepartmentInfoEntity, GetDepartmentListOutput>.Map(root);
                    resultList.Add(rootInfo);

                    GetChildDepartment(rootInfo, departments, resultList);
                }
                else
                {
                    resultList = MapperHelper<DepartmentInfoEntity, GetDepartmentListOutput>.MapList(departments);
                }
            }
            return resultList;
        }

        /// <summary>
        /// 获取子节点
        /// </summary>
        /// <param name="root"></param>
        /// <param name="dataList"></param>
        /// <param name="resultList"></param>
        private void GetChildDepartment(GetDepartmentListOutput root, List<DepartmentInfoEntity> dataList, List<GetDepartmentListOutput> resultList)
        {
            var childrens = dataList.Where(x => x.ParentId == root.Id).OrderBy(x => x.Sort).ToList();
            if (childrens.Any())
            {
                var childrenList = MapperHelper<DepartmentInfoEntity, GetDepartmentListOutput>.MapList(childrens);
                resultList.AddRange(childrenList);

                foreach (var item in childrenList)
                {
                    GetChildDepartment(item, dataList, resultList);
                }
            }
        }


        /// <summary>
        /// 获取部门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BaseApiResult<GetDepartmentOutput>> GetDepartment(GetDepartmentInput input) {

            return await HandleAsync(input, async () =>
            {
                var department = await _departmentRepository.GetAsync(x => x.Id.Equals(input.Id.Value), readOnly: input.ReadOnly);
                if (department == null)
                {
                    throw new ApplicationsException("部门不存在");
                }
                var res = MapperHelper<DepartmentInfoEntity, GetDepartmentOutput>.Map(department);

                return res;
            });
        } 



    }
}
